package com.github.sbb.sherry.console.interceptor;


import static com.github.sbb.sherry.console.interceptor.LogInfo.LOG_NO_SIGN;

import java.util.Optional;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * The type Global interceptor.
 */
@Slf4j
@Component
@Order(-1)
public class GlobalInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    // 如果取不到直接用 UUID
    String logNo = Optional.ofNullable(request.getHeader(LOG_NO_SIGN)).orElseGet(() -> UUID.randomUUID().toString());
    LogInfo logInfo = new LogInfo(logNo);
    logInfo.setLogNo(logNo);
    MDC.put(LOG_NO_SIGN, logNo);
    return true;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    AppLogHolder.remove();
  }
}
